package com.oauth.user.redis;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class AccountRedisService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    
    private String key(String clientId, String account) {
        return clientId + "-" + account;
    }
    
    public void put(String clientId, String account, String token) {
        String key = key(clientId, account);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(key, token, Duration.ofMinutes(5));
    }
    
    public String get(String clientId, String account) {
        String key = key(clientId, account);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String token = ops.get(key);
        return token;
    }
    
    public void del(String clientId, String account) {
        String key = key(clientId, account);
        redisTemplate.delete(key);
    }
    
    public void refresh(String clientId, String account) {
        String key = key(clientId, account);
        if(redisTemplate.hasKey(key)) {
            redisTemplate.expire(key, 5, TimeUnit.MINUTES);
        }
    }
}
